package com.web.controller.web;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.web.dao.*;
import com.web.domain.MUser;
import com.web.domain.WebResponse;
import com.web.domain.dataTable.BootstrapTableColumns;
import com.web.domain.dataTable.BootstrapTableResponse;
import com.web.entity.*;
import com.web.manager.FileUpLoadManager;
import com.xkk.utils.UUIDUtil;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.InputStream;
import java.math.BigDecimal;
import java.util.Date;

/**
 * @author FDjavaone
 * @date 2017/10/19
 */
@Slf4j
@Controller
public class WebAgentHomeController {
    @Autowired
    private RegionRecordMapper regionRecordMapper;
    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private UserAccountMapper userAccountMapper;
    @Autowired
    private UserAccountRecordMapper userAccountRecordMapper;
    @Autowired
    private AgentWithdrawApplyMapper agentWithdrawApplyMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PlatformMapper platformMapper;
    @Autowired
    private FileUpLoadManager fileUpLoadManager;
    @Autowired
    private CompanyBonusDetailMapper companyBonusDetailMapper;


    @Data
    public static class AgentDto {
        private String regionArea;
        private BigDecimal incomeBal;


    }

    @RequestMapping(value = "agenthome",
            method = RequestMethod.GET)
    public String agenthome(Model model, HttpServletRequest request) {
        return "agenthome";
    }

    @RequestMapping(value = "sysa/myincome",
            method = RequestMethod.GET)
    public String myincome(Model model, HttpServletRequest request) {
        return "agentIncomeRecord";
    }

    @RequestMapping(value = "sysa/mystore",
            method = RequestMethod.GET)
    public String agentStore(Model model, HttpServletRequest request) {
        return "agentStore";
    }

    @RequestMapping(value = "sysa/mywithdraw",
            method = RequestMethod.GET)
    public String agentWithdraw(Model model, HttpServletRequest request) {
        return "agentWithdraw";
    }

    @RequestMapping(value = "sysf/transfer",
            method = RequestMethod.GET)
    public String AgentWithdrawDeal(Model model, HttpServletRequest request) {
        return "AgentWithdrawDeal";
    }

    @RequestMapping("agentHomeCount")
    @ResponseBody
    public WebResponse agentHomeCount() {
        MUser user = (MUser) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        UserAccount userAccount = userAccountMapper.selectByUid(user.getId());
        RegionRecord regionRecord = regionRecordMapper.selectByUid(user.getId());
        AgentDto agentDto = new AgentDto();
        if (regionRecord == null) {
            agentDto.setRegionArea("暂无");
        } else {
            if (regionRecord.getLevel() == 1) {
                agentDto.setRegionArea(regionRecord.getProvince());
            } else if (regionRecord.getLevel() == 2) {
                agentDto.setRegionArea(regionRecord.getProvince() + regionRecord.getCity());
            } else if (regionRecord.getLevel() == 3) {
                agentDto.setRegionArea(regionRecord.getProvince() + regionRecord.getCity() + regionRecord.getRegion());
            }
        }
        agentDto.setIncomeBal(userAccount.getProfit());
        return WebResponse.ok("获取成功", agentDto);
    }

    @Data
    public static class AgentColumns extends BootstrapTableColumns {
        private Long uAid;
        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private Date begin_createTime;
        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private Date end_createTime;
    }


    @RequestMapping("sysa/getMyAgentLogs")
    @ResponseBody
    public BootstrapTableResponse getMerchantAgentLogs(AgentColumns agentColumns) {
        MUser user = (MUser) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        UserAccount userAccount = userAccountMapper.selectByUid(user.getId());
        agentColumns.setUAid(userAccount.getId());
        PageHelper.startPage(agentColumns.getPageNumber(), agentColumns.getPageSize());
        Page<UserAccountRecord> page = userAccountRecordMapper.selectMerchantAgentLogsById(agentColumns);
        BootstrapTableResponse bootstrapTableResponse = new BootstrapTableResponse();
        bootstrapTableResponse.setResult(page.getResult());
        bootstrapTableResponse.setTotalCount(page.getTotal());
        return bootstrapTableResponse;
    }


    @GetMapping("sysa/getMyAgentStores")
    @ResponseBody
    public BootstrapTableResponse getStores(WebStoreController.StoreColumns storeColumns) {
        MUser user = (MUser) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        RegionRecord regionRecord = regionRecordMapper.selectByUid(user.getId());
        PageHelper.startPage(storeColumns.getPageNumber(), storeColumns.getPageSize());
        Page<Store> page = new Page<>();
        if (regionRecord != null) {
            if (regionRecord.getLevel() == 1) {
                storeColumns.setProvince(regionRecord.getProvince());
            } else if (regionRecord.getLevel() == 2) {
                storeColumns.setProvince(regionRecord.getProvince());
                storeColumns.setCity(regionRecord.getCity());
            } else if (regionRecord.getLevel() == 3) {
                storeColumns.setProvince(regionRecord.getProvince());
                storeColumns.setCity(regionRecord.getCity());
                storeColumns.setRegion(regionRecord.getRegion());
            }
            page = storeMapper.selectAllStore(storeColumns);
        }
        BootstrapTableResponse bootstrapTableResponse = new BootstrapTableResponse();
        bootstrapTableResponse.setResult(page.getResult());
        bootstrapTableResponse.setTotalCount(page.getTotal());
        return bootstrapTableResponse;
    }


    @Data
    public static class AgentWithdrawColumns extends BootstrapTableColumns {
        private Long id;
        private Integer status;
        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private Date begin_createTime;
        @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
        private Date end_createTime;
    }


    @RequestMapping("sysa/getMyAgentWithdrawApply")
    @ResponseBody
    public BootstrapTableResponse getWithdrawApply(AgentWithdrawColumns withdrawColumns) {
        MUser user = (MUser) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        withdrawColumns.setId(user.getId());
        PageHelper.startPage(withdrawColumns.getPageNumber(), withdrawColumns.getPageSize());
        Page<AgentWithdrawApply> page = agentWithdrawApplyMapper.selectMyWithdraws(withdrawColumns);
        BootstrapTableResponse bootstrapTableResponse = new BootstrapTableResponse();
        bootstrapTableResponse.setResult(page.getResult());
        bootstrapTableResponse.setTotalCount(page.getTotal());
        return bootstrapTableResponse;
    }


    @RequestMapping("/sysa/withdraw/add")
    @ResponseBody
    public WebResponse withdrawApplyAdd(AgentWithdrawApply agentWithdrawApply) {
        MUser user = (MUser) SecurityContextHolder.getContext()
                .getAuthentication()
                .getPrincipal();
        UserAccount userAccount = userAccountMapper.selectByUid(user.getId());
        User user1 = userMapper.selectByPrimaryKey(user.getId());
        Date date = new Date();
        if (userAccount.getProfit().compareTo(agentWithdrawApply.getAmt()) != -1) {


            //分润账户明细生成（在后台确认已经打款时再添加）
            userAccountMapper.profitSubtract(agentWithdrawApply.getAmt(), user1.getId());

            UserAccountRecord userAccountRecord = new UserAccountRecord();
            userAccountRecord.setCreateTime(date);
            userAccountRecord.setModifyTime(date);
            userAccountRecord.setDetail("申请提现金额：-" + agentWithdrawApply.getAmt()+"元。");
            userAccountRecord.setuAid(userAccount.getId());
            userAccountRecord.setBal(userAccountMapper.selectByPrimaryKey(userAccount.getId()).getProfit().toString());
            userAccountRecord.setName(user1.getUsername());
            userAccountRecord.setPhone(user1.getPhone());
            userAccountRecord.setFromNum("");
            userAccountRecordMapper.insertSelective(userAccountRecord);

            agentWithdrawApply.setName(user1.getUsername());
            agentWithdrawApply.setPhone(user1.getPhone());
            agentWithdrawApply.setuId(user1.getId());
            agentWithdrawApply.setStatus(0);
            agentWithdrawApply.setRecordId(userAccountRecord.getId());
            agentWithdrawApply.setCreateTime(date);
            agentWithdrawApply.setModifyTime(date);
            agentWithdrawApplyMapper.insertSelective(agentWithdrawApply);

            return WebResponse.ok("提现申请成功！");
        } else {
            return WebResponse.fail("账户余额不足申请提现失败！");
        }
    }

    @RequestMapping("sysa/getAgentWithdrawApply")
    @ResponseBody
    public BootstrapTableResponse getWithdrawApply(WebWithdrawController.WithdrawColumns withdrawColumns) {

        if (StringUtils.isNotBlank(withdrawColumns.getName())) {
            withdrawColumns.setName("%" + withdrawColumns.getName() + "%");
        }
        if (StringUtils.isNotBlank(withdrawColumns.getPhone())) {
            withdrawColumns.setPhone("%" + withdrawColumns.getPhone() + "%");
        }
        PageHelper.startPage(withdrawColumns.getPageNumber(), withdrawColumns.getPageSize());
        Page<AgentWithdrawApply> page = agentWithdrawApplyMapper.selectAllwithdraws(withdrawColumns);
        BootstrapTableResponse bootstrapTableResponse = new BootstrapTableResponse();
        bootstrapTableResponse.setResult(page.getResult());
        bootstrapTableResponse.setTotalCount(page.getTotal());
        return bootstrapTableResponse;
    }


    @RequestMapping(value = "/sysa/agentWithdrawApply/confirm")
    @ResponseBody
    public WebResponse confirm(AgentWithdrawApply agentWithdrawApply, MultipartFile file) {
        Date date = new Date();
        try {
            AgentWithdrawApply apply = agentWithdrawApplyMapper.selectByPrimaryKey(agentWithdrawApply.getId());
            InputStream is = file.getInputStream();
            String str = fileUpLoadManager.upload(is, UUIDUtil.getUUID() + file.getOriginalFilename());
            agentWithdrawApply.setAccount("http://" + str);
            agentWithdrawApply.setStatus(1);
            agentWithdrawApply.setModifyTime(date);
            agentWithdrawApplyMapper.updateByPrimaryKeySelective(agentWithdrawApply);

            //对应扣除奖金池的金额
            platformMapper.bonusPoolSubstract(apply.getAmt(), 1L);
            CompanyBonusDetail companyBonusDetail = new CompanyBonusDetail();
            companyBonusDetail.setCreateTime(date);
            companyBonusDetail.setModifyTime(date);
            companyBonusDetail.setContent("代理商用户：" + apply.getName() + apply.getPhone() + "提现" + apply.getAmt() + "元，提现id：" + apply.getId());
            companyBonusDetail.setDetail("-" + apply.getAmt());
            companyBonusDetail.setBal(platformMapper.selectByPrimaryKey(1L).getBonusPool().toString());
            companyBonusDetail.setFromNum(String.valueOf(apply.getId()));
            companyBonusDetail.setDescription("代理商用户：" + apply.getName() + apply.getPhone() + "提现" + apply.getAmt() + "元，提现id：" + apply.getId());
            companyBonusDetail.setName(apply.getName());
            companyBonusDetail.setPhone(apply.getPhone());
            companyBonusDetailMapper.insertSelective(companyBonusDetail);

            if(agentWithdrawApply.getRecordId()!=0){
                UserAccountRecord userAccountRecord =userAccountRecordMapper.selectByPrimaryKey(agentWithdrawApply.getRecordId());
                userAccountRecord.setModifyTime(date);
                userAccountRecord.setDetail(userAccountRecord.getDetail()+"(已打款)");
                userAccountRecordMapper.updateByPrimaryKeySelective(userAccountRecord);
            }

            return WebResponse.ok("确认打款成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return WebResponse.fail(WebResponse.CF);
        }
    }


    @RequestMapping(value = "/sysa/agentWithdrawApply/refuse")
    @ResponseBody
    public WebResponse refuse(AgentWithdrawApply agentWithdrawApply) {
        Date date = new Date();
        try {
            AgentWithdrawApply apply = agentWithdrawApplyMapper.selectByPrimaryKey(agentWithdrawApply.getId());
            UserAccount account = userAccountMapper.selectByUid(apply.getuId());
            User member = userMapper.selectByPrimaryKey(account.getuId());
            // 审核拒绝归还对应账户冻结金额
            userAccountMapper.profitAdd(apply.getAmt(), member.getId());

            UserAccountRecord userAccountRecord = new UserAccountRecord();
            userAccountRecord.setCreateTime(date);
            userAccountRecord.setModifyTime(date);
            userAccountRecord.setDetail("提现驳回归还申请金额：+" + apply.getAmt()+"元。");
            userAccountRecord.setuAid(account.getId());
            userAccountRecord.setBal(userAccountMapper.selectByPrimaryKey(account.getId()).getProfit().toString());
            userAccountRecord.setName(member.getUsername());
            userAccountRecord.setPhone(member.getPhone());
            userAccountRecord.setFromNum("");
            userAccountRecordMapper.insertSelective(userAccountRecord);

            agentWithdrawApply.setStatus(2);
            agentWithdrawApply.setModifyTime(date);
            agentWithdrawApplyMapper.updateByPrimaryKeySelective(agentWithdrawApply);
            return WebResponse.ok("操作成功！");
        } catch (Exception e) {
            e.printStackTrace();
            return WebResponse.fail(WebResponse.CF);
        }
    }

}
